#!/usr/bin/perl

use warnings;
use strict;

#####################################################################################################
## Description: This file extracts all warning messages from the output of Cadence RC. It uses the 
## 				latest log file as input.
## Author: Alicia Klinefelter
## Created: 09/29/2013
## Last Modified: 09/30/2013																	   
##																								   
## The output file is called warnings_enc.txt					   																	  
## To run:																						   
## perl warnings_parse_enc.pl								   
#####################################################################################################

#******************************* Define names of input/output files ********************************#
my $infile_root = "encounter.log";
my $infile = "encounter.log";
my $outfile = "./warnings_enc.txt";

#******************************** Open files *********************************#
open(OUT, '>', "$outfile") || die("Could not open file!");


#****** Variables ******#
my $line = "";
my @tokens = ();
my @tokens2 = ();
my $tokens;
my $still_warning = 0;
my $sub_line;
my $i = 0;
my $j;
my $loop_stop = 0;
my $line_num = 1;

# Check for the latest log file name 
while($loop_stop == 0) {
	if (-e $infile) {
		$i++;
		$infile = $infile_root . "$i";
	} else {
		if ($i == 1) {
			$infile = $infile_root;
			$loop_stop = 1;	
		} else {
			$j = $i - 1;
			$infile = $infile_root . "$j";
			$loop_stop = 1;	
		}
	}
}
open(IN, '<', "$infile") || die("Could not open file!");
print OUT "**************** Log file: $infile ****************\n\n";

while ($line = <IN>) {
	# If the line is empty or doesn't have a memory map, just skip to the next line
	if ($line =~ /^\s*$/) {
		# blank line, ignore
    }
    elsif (length($line) > 0) {
		chomp($line);
		# Split file
		@tokens = split(' ', $line);
		# Get the number of tokens in the array:
		$tokens = @tokens;
		
		# See if the line begins with the word "WARNING"
		chomp($tokens[0]);
		if ($tokens[0] =~ "WARN") { 
			$still_warning = 1;
			print OUT "Line $line_num: $line\n";
			# Check for multi-line warning messages
			while ($still_warning == 1) {
				$sub_line = <IN>;
				if ($sub_line =~ /^\s*$/) {
					# blank line, ignore
				} else {
					$line_num++;
					chomp($sub_line);
					@tokens2 = split(' ', $sub_line);
					# Check for warning messages that begin right after other warning messages
					if ($tokens2[0] =~ "WARN") {
						print OUT "\nLine $line_num: $sub_line\n";
					}
					else {
						$still_warning = 0;
						print OUT "\n";
					}
				}
			}
		}
    }
	$line_num++;
}

close IN;
close OUT;	







